package com.example.aigc_education.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.aigc_education.common.BusinessException;
import com.example.aigc_education.domain.request.UdTodoCompletedRequest;
import com.example.aigc_education.domain.TodoV2;
import com.example.aigc_education.domain.request.AddTodoRequest;
import com.example.aigc_education.domain.request.UpdateTodoRequest;
import com.example.aigc_education.domain.vo.*;
import com.example.aigc_education.enums.TodoCompletedType;
import com.example.aigc_education.enums.TodoType;
import com.example.aigc_education.mapper.TodoV2Mapper;
import com.example.aigc_education.service.TodoV2Service;
import com.example.aigc_education.service.converter.TodoConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
* @author hongy
* @description 针对表【stu_todo_v2】的数据库操作Service实现
* @createDate 2025-02-24 18:03:58
*/
@Service
public class TodoV2ServiceImpl extends ServiceImpl<TodoV2Mapper, TodoV2>
    implements TodoV2Service {

    @Autowired
    private TodoV2Mapper todoV2Mapper;

    @Autowired
    private TodoConverter todoConverter;

    @Override
    public IdVO addTodo(Long userId, AddTodoRequest addChecklistRequest) {
        try {
            TodoV2 todoV2 = todoConverter.addTodoRequestToTodoV2(addChecklistRequest);
            todoV2.setUserId(userId);
            todoV2Mapper.insert(todoV2);
            return new IdVO(todoV2.getTodoId());
        }catch (Exception e){
            throw new BusinessException("添加todo失败");
        }

    }

    @Override
    public UpdateTodoVO updateTodo(UpdateTodoRequest updateTodoRequest) {
        try {
            TodoV2 todoV2 = todoConverter.updateTodoRequestToTodoV2(updateTodoRequest);
            todoV2Mapper.updateById(todoV2);
            return todoConverter.updateTodoRequestToUpdateTodoVO(updateTodoRequest);
        }catch (Exception e){
            throw new BusinessException("修改todo失败");
        }
    }

//    @Override
//    public UdTodoCompletedVO updateTodoCompleted(UdTodoCompletedRequest udTodoCompletedRq) {
//        try {
//            LambdaUpdateWrapper<TodoV2> updateWrapper = new LambdaUpdateWrapper<>();
//            updateWrapper.eq(TodoV2::getTodoId,udTodoCompletedRq.getTodoId())
//                    .set(TodoV2::getCompleted,TodoCompletedType.fromTitle(udTodoCompletedRq.getCompleted()).getValue());
//            todoV2Mapper.update(null,updateWrapper);
//            return new UdTodoCompletedVO(udTodoCompletedRq.getTodoId(), udTodoCompletedRq.getCompleted());
//        }catch (Exception e){
//            throw new BusinessException("修改todo完成状态失败");
//        }
//    }

    @Override
    public UdTodoCompletedVO updateTodoCompleted(UdTodoCompletedRequest udTodoCompletedRq) {
        try {
            LambdaUpdateWrapper<TodoV2> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.eq(TodoV2::getTodoId,udTodoCompletedRq.getTodoId())
                    .set(TodoV2::getCompleted,TodoCompletedType.COMPLETE.getValue());
            todoV2Mapper.update(null,updateWrapper);
            return new UdTodoCompletedVO(udTodoCompletedRq.getTodoId(),TodoCompletedType.COMPLETE.getTitle());
        }catch (Exception e){
            throw new BusinessException("修改todo完成状态失败");
        }
    }

    @Override
    public Boolean deleteTodos(Long[] ids) {
//        用mybatisPlus的Wrapper将status改为0
        LambdaUpdateWrapper<TodoV2> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.in(TodoV2::getTodoId,ids)
                .set(TodoV2::getStatus,0);
        return this.update(updateWrapper);
    }

    /**
     * 获取今天ddl和优先级排序的待办
     *
     * @return 返回今天ddl和优先级排序的待办
     */
    @Override
    public Map<String, List<TodoVO>> getTodayTodos(Long userId) {
        try {
            LambdaQueryWrapper<TodoV2> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(TodoV2::getUserId,userId)
                    .eq(TodoV2::getStatus,1)
                    .eq(TodoV2::getDeadline, LocalDate.now())
                    .orderByDesc(TodoV2::getCompleted)
                    .orderByAsc(TodoV2::getPriority);
            List<TodoV2> todoV2s = todoV2Mapper.selectList(queryWrapper);
            List<TodoVO> allTodos = todoConverter.todoV2sToTodoVOs(todoV2s);
            Map<String, List<TodoVO>> result = allTodos.stream()
                    .collect(Collectors.groupingBy(todoVO ->
                            TodoCompletedType.COMPLETE.getTitle().equals(todoVO.getCompleted()) ? "completed" : "uncompleted"));

            return result;

        }catch (Exception e){
            throw new BusinessException("获取今日todo列表失败");
        }
    }

    @Override
    public GetAllTodosVO getAllTodos(Long userId) {
        try {
            LambdaQueryWrapper<TodoV2> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(TodoV2::getUserId,userId)
                    .eq(TodoV2::getStatus,1)
                    .orderByAsc(TodoV2::getCompleted)
                    .orderByAsc(TodoV2::getPriority);
            List<TodoV2> todoV2s = todoV2Mapper.selectList(queryWrapper);

            //分别统计所有，紧急，今日，已完成的待办数目
            //total
            Long total =(long) todoV2s.size();

            //today
            queryWrapper.eq(TodoV2::getDeadline, LocalDate.now());
            Long today = todoV2Mapper.selectCount(queryWrapper);

            //urgent
            Integer[] todoType = new Integer[]{TodoType.IMPORTANT_URGENT.getValue(),TodoType.URGENT_NOT_IMPORTANT.getValue()};
            LambdaQueryWrapper<TodoV2> urgentWrapper = new LambdaQueryWrapper<>();
            urgentWrapper.eq(TodoV2::getUserId,userId)
                    .eq(TodoV2::getStatus,1)
                    .in(TodoV2::getTodoType, todoType);
            Long urgent = todoV2Mapper.selectCount(urgentWrapper);

            //completed
            LambdaQueryWrapper<TodoV2> completedWrapper = new LambdaQueryWrapper<>();
            completedWrapper.eq(TodoV2::getUserId,userId)
                    .eq(TodoV2::getStatus,1)
                    .eq(TodoV2::getCompleted, TodoCompletedType.COMPLETE.getValue());
            Long completed = todoV2Mapper.selectCount(completedWrapper);

            return new GetAllTodosVO(new GetAllTodosVO.Statistics(total,urgent,today,completed),
                    todoConverter.todoV2sToTodoVOs(todoV2s));

        }catch (Exception e){
            throw new BusinessException("获取所有todo列表失败");
        }
    }
}




